package com.blahti.example.drag2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;


import com.blahti.example.drag2.R;
import com.icons.draw.view.LocationViewers;

import data.ParkingDB;
import data.ParkingSpot;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * This activity presents a screen on which images can be added and moved around.
 * It also defines areas on the screen where the dragged views can be dropped. Feedback is
 * provided to the user as the objects are dragged over these drop zones.
 *
 * <p> Like the DragActivity in the previous version of the DragView example application, the
 * code here is derived from the Android Launcher code.
 * 
 */

public class DragActivityV2 extends Activity 
implements View.OnLongClickListener, View.OnClickListener, View.OnTouchListener
{


	static final int PROGRESS_DIALOG = 0;
	ProgressDialog progressDialog;
	final DragActivityV2 thisActivity = this;
	private static final int ENABLE_S2_MENU_ID = Menu.FIRST;
	private static final int DISABLE_S2_MENU_ID = Menu.FIRST + 1;
	private static final int ADD_OBJECT_MENU_ID = Menu.FIRST + 2;
	private static final int CHANGE_TOUCH_MODE_MENU_ID = Menu.FIRST + 3;
	private TextView selection;
	SharedPreferences ref;
	public static final String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss";

	/**
	 */
	// Variables

	private DragController mDragController;   // Object that sends out drag-drop events while a view is being moved.
	private DragLayer mDragLayer;             // The ViewGroup that supports drag-drop.
	private DropSpot mSpot2;                  // The DropSpot that can be turned on and off via the menu.
	private boolean mLongClickStartsDrag = true;    // If true, it takes a long click to start the drag operation.
	// Otherwise, any touch event starts a drag.
	DropSpot DropSpotArray[];
	//DropSpot DropSpotArray_L[];
	ParkingSpot parkingArray[];
	//ParkingSpot parkingArrayL[];
	static int  available=0;
	static int unAvailable=1;
	static int unKnown=2;
	ParkingDB parking_db;
	Button button2;



	public static final boolean Debugging = false;

	/**
	 */
	// Methods

	/**
	 * onCreate - called when the activity is first created.
	 * 
	 * Creates a drag controller and sets up three views so click and long click on the views are sent to this activity.
	 * The onLongClick method starts a drag sequence.
	 *
	 */

	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		mDragController = new DragController(this);
		DropSpotArray=new DropSpot[10];
		setContentView(R.layout.editmap);
		
		parking_db=ParkingDB.getInstance();
		
		Bundle extras=getIntent().getExtras();
		
		parking_db.listIndex_A=extras.getInt("listIndex_A");
		parking_db.listIndex_B=extras.getInt("listIndex_B");
		
		parking_db.IndexArray_A[0]=extras.getInt("A0");
		parking_db.IndexArray_A[1]=extras.getInt("A1");
		parking_db.IndexArray_A[2]=extras.getInt("A2");
		parking_db.IndexArray_A[3]=extras.getInt("A3");
		parking_db.IndexArray_A[4]=extras.getInt("A4");
		
		parking_db.IndexArray_B[0]=extras.getInt("B0");
		parking_db.IndexArray_B[1]=extras.getInt("B1");
		parking_db.IndexArray_B[2]=extras.getInt("B2");
		parking_db.IndexArray_B[3]=extras.getInt("B3");
		parking_db.IndexArray_B[4]=extras.getInt("B4");
		
		setupViews ();
		setColors();
		selection=(TextView)findViewById(R.id.street);
		selection.setBackgroundColor(Color.BLACK);
		if(parking_db.userStreet!=null)
			selection.setText(parking_db.userStreet);
		else
			selection.setText("street name");
		button2 = (Button) findViewById(R.id.ButtonSAVE);
		button2.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				Log.d("press button","$$$$$$$$$$$$$$$$$$$$ button");
				Drawable d= getResources().getDrawable(R.drawable.edit);
				button2.setBackgroundDrawable(d);
				if((parking_db.serverOn)&&(parking_db.listIndex_A!=-1)&&(parking_db.listIndex_B!=-1))
				    LocationViewers.mapView.postInvalidate();
					if(parking_db.myParking==true)
					{
						SharedPreferences ref= getSharedPreferences("com.ruthy.parkApp",MODE_PRIVATE);
						SharedPreferences.Editor ed=ref.edit();
						ed.putString("userSpotLat",Double.toString( parking_db.mySpotLat));
						ed.putString("userSpotLong",Double.toString( parking_db.mySpotLong));
						ed.commit();
						Toast.makeText (getApplicationContext(), "Your parking was saved", Toast.LENGTH_LONG).show ();
					}
					performPostRequest();
					for(int i=0;i<5;i++)
					{
						if((parking_db.listIndex_A!=-1)&&(parking_db.IndexArray_A[i]!=-1))
						{
							Log.d("____________________________",Integer.toString(parking_db.parkingVector.get(parking_db.listIndex_A).list.get(parking_db.IndexArray_A[i]).parkingStatus));
                            int color=DropSpotArray[i].getSavedBackground();
                            switch (color)
                            {
                            case Color.BLUE:
                            	parking_db.parkingVector.get(parking_db.listIndex_A).list.get(parking_db.IndexArray_A[i]).parkingStatus=available;
                            	break;
                            case Color.RED:
                            	parking_db.parkingVector.get(parking_db.listIndex_A).list.get(parking_db.IndexArray_A[i]).parkingStatus=unAvailable;
                            	break;
                            case Color.YELLOW:
                            	parking_db.parkingVector.get(parking_db.listIndex_A).list.get(parking_db.IndexArray_A[i]).parkingStatus=unKnown;
                            	break;
                            default:
                            	parking_db.parkingVector.get(parking_db.listIndex_A).list.get(parking_db.IndexArray_A[i]).parkingStatus=unKnown;
                            	break;
                            }
						}
						else
							Log.d("__________________________________","-1");
					}
						for(int i=5;i<10;i++)
						{
							if((parking_db.listIndex_B!=-1)&&(parking_db.IndexArray_B[i-5]!=-1))
							{
								Log.d("_____________________________",Integer.toString(parking_db.parkingVector.get(parking_db.listIndex_B).list.get(parking_db.IndexArray_B[i-5]).parkingStatus ));
	                            int color=DropSpotArray[i].getSavedBackground();
	                            switch (color)
	                            {
	                            case Color.BLUE:
	                            	parking_db.parkingVector.get(parking_db.listIndex_B).list.get(parking_db.IndexArray_B[i-5]).parkingStatus=available;
	                            	break;
	                            case Color.RED:
	                            	parking_db.parkingVector.get(parking_db.listIndex_B).list.get(parking_db.IndexArray_B[i-5]).parkingStatus=unAvailable;
	                            	break;
	                            case Color.YELLOW:
	                            	parking_db.parkingVector.get(parking_db.listIndex_B).list.get(parking_db.IndexArray_B[i-5]).parkingStatus=unKnown;
	                            	break;
	                            default:
	                            	parking_db.parkingVector.get(parking_db.listIndex_B).list.get(parking_db.IndexArray_B[i-5]).parkingStatus=unKnown;
	                            	break;
	                            }

							}
							else
								Log.d("_________________________________","-1");
						}
				
			}
		});	
	}
	public void onRestart(){
		Log.d("DragActivity2","onRestart");
		super.onRestart();
		SharedPreferences ref= getSharedPreferences("com.ruthy.parkApp",MODE_PRIVATE);
		if(ref.getString("SavedDialog", "0").equals("show"))
		{
			Toast.makeText (getApplicationContext(), "Changes saved, for posting press on 'Edit Map' button", Toast.LENGTH_LONG).show ();
			SharedPreferences.Editor ed=ref.edit();
			ed.putString("SavedDialog","not");
			ed.commit();
		}


	}

	/**
	 * Build a menu for the activity.
	 *
	 */    
	/*
public boolean onCreateOptionsMenu (Menu menu) 
{
    super.onCreateOptionsMenu(menu);

    menu.add(0, ENABLE_S2_MENU_ID, 0, "Enable Spot2").setShortcut('1', 'c');
    menu.add(0, DISABLE_S2_MENU_ID, 0, "Disable Spot2").setShortcut('2', 'c');
    menu.add(0, ADD_OBJECT_MENU_ID, 0, "Add View").setShortcut('9', 'z');
    menu.add (0, CHANGE_TOUCH_MODE_MENU_ID, 0, "Change Touch Mode");

    return true;
}
	 */
	/**
	 * Handle a click on a view.
	 *
	 */    

	public void onClick(View v) 
	{
		if (mLongClickStartsDrag) {
			// Tell the user that it takes a long click to start dragging.
		//	toast ("Press and hold to drag the car to your parking spot.");
		}
	}

	/**
	 * Handle a long click.
	 *
	 * @param v View
	 * @return boolean - true indicates that the event was handled
	 */    

	public boolean onLongClick(View v) 
	{
		if (mLongClickStartsDrag) {

			//trace ("onLongClick in view: " + v + " touchMode: " + v.isInTouchMode ());

			// Make sure the drag was started by a long press as opposed to a long click.
			// (Note: I got this from the Workspace object in the Android Launcher code. 
			//  I think it is here to ensure that the device is still in touch mode as we start the drag operation.)
			if (!v.isInTouchMode()) {
				toast ("isInTouchMode returned false. Try touching the view again.");
				return false;
			}
			return startDrag (v);
		}

		// If we get here, return false to indicate that we have not taken care of the event.
		return false;
	}

	/**
	 * Perform an action in response to a menu item being clicked.
	 *
	 */
	
	/**
	 * This is the starting point for a drag operation if mLongClickStartsDrag is false.
	 * It looks for the down event that gets generated when a user touches the screen.
	 * Only that initiates the drag-drop sequence.
	 *
	 */    

	public boolean onTouch (View v, MotionEvent event) 
	{

		// If we are configured to start only on a long click, we are not going to handle any events here.
		if (mLongClickStartsDrag) return false;

		boolean handledHere = false;

		final int action = event.getAction();

		// In the situation where a long click is not needed to initiate a drag, simply start on the down event.
		if (action == MotionEvent.ACTION_DOWN) {
			handledHere = startDrag (v);
		}

		return handledHere;
	}

	/**
	 * Start dragging a view.
	 *
	 */    

	public boolean startDrag (View v)
	{
		// Let the DragController initiate a drag-drop sequence.
		// I use the dragInfo to pass along the object being dragged.
		// I'm not sure how the Launcher designers do this.
		Object dragInfo = v;
		mDragController.startDrag (v, mDragLayer, dragInfo, DragController.DRAG_ACTION_MOVE);
		return true;
	}
	private void setColors()
	{
		int status=2;
		if(parking_db.serverOn)
		{
			for(int i=0;i<10;i++)
			{
				if(i<5)
				{
					if((parking_db.IndexArray_A[i]!=-1)&&(parking_db.listIndex_A!=-1))
						status=parking_db.parkingVector.get(parking_db.listIndex_A).list.get(parking_db.IndexArray_A[i]).parkingStatus;

				}
				else
				{
					if((parking_db.IndexArray_B[i-5]!=-1)&&(parking_db.listIndex_B!=-1))
						status=parking_db.parkingVector.get(parking_db.listIndex_B).list.get(parking_db.IndexArray_B[i-5]).parkingStatus;
				}

				switch(status)
				{
				case 0:
					DropSpotArray[i].setBackgroundColor(Color.BLUE);
					DropSpotArray[i].setSavedBackground(Color.BLUE);
					break;
				case 1: 
					DropSpotArray[i].setBackgroundColor(Color.RED);
					DropSpotArray[i].setSavedBackground(Color.RED);
					break;
				case 2:  
					DropSpotArray[i].setBackgroundColor(Color.YELLOW);
					DropSpotArray[i].setSavedBackground(Color.YELLOW);
					break;
				default:
					DropSpotArray[i].setBackgroundColor(Color.BLACK);
					DropSpotArray[i].setSavedBackground(Color.BLACK);
					break;
				}
			}
		}



	}

	/**
	 * Finds all the views we need and configure them to send click events to the activity.
	 *
	 */
	private void setupViews() 
	{
		DragController dragController = mDragController;

		mDragLayer = (DragLayer) findViewById(R.id.drag_layer);
		mDragLayer.setDragController(dragController);
		dragController.addDropTarget (mDragLayer);

		ImageView car = (ImageView) findViewById (R.id.Image1);
		//ImageView i2 = (ImageView) findViewById (R.id.Image2);

		car.setOnClickListener(this);
		car.setOnLongClickListener(this);
		car.setOnTouchListener(this);
		/*
    i2.setOnClickListener(this);
    i2.setOnLongClickListener(this);
    i2.setOnTouchListener(this);
		 */
		TextView tv = (TextView) findViewById (R.id.Text1);
		tv.setOnLongClickListener(this);
		tv.setOnTouchListener(this);

		// Set up some drop targets and enable them by connecting them to the drag layer
		// and the drag controller.
		// Note: If the dragLayer is not set, the drop spot will not accept drops.
		// That is the initial state of the second drop spot.



		DropSpotArray[0] = (DropSpot) mDragLayer.findViewById (R.id.drop_spot1);
		DropSpotArray[0].setup (mDragLayer, dragController, R.color.drop_target_color1);
		DropSpotArray[0].id=0;

		DropSpotArray[1] = (DropSpot) mDragLayer.findViewById (R.id.drop_spot2);
		DropSpotArray[1].setup (mDragLayer, dragController, R.color.drop_target_color2);
		DropSpotArray[1].id=1;

		DropSpotArray[2] = (DropSpot) mDragLayer.findViewById (R.id.drop_spot3);
		DropSpotArray[2].setup (mDragLayer, dragController, R.color.drop_target_color1);
		DropSpotArray[2].id=2;

		DropSpotArray[3] = (DropSpot) mDragLayer.findViewById (R.id.drop_spot4);
		DropSpotArray[3].setup (mDragLayer, dragController, R.color.drop_target_color2);
		DropSpotArray[3].id=3;

		DropSpotArray[4] = (DropSpot) mDragLayer.findViewById (R.id.drop_spot5);
		DropSpotArray[4].setup (mDragLayer, dragController, R.color.drop_target_color1);
		DropSpotArray[4].id=4;

		DropSpotArray[5] = (DropSpot) mDragLayer.findViewById (R.id.drop_spot6);
		DropSpotArray[5].setup (mDragLayer, dragController, R.color.drop_target_color1);
		DropSpotArray[5].id=5;

		DropSpotArray[6] = (DropSpot) mDragLayer.findViewById (R.id.drop_spot7);
		DropSpotArray[6].setup (mDragLayer, dragController, R.color.drop_target_color2);
		DropSpotArray[6].id=6;

		DropSpotArray[7] = (DropSpot) mDragLayer.findViewById (R.id.drop_spot8);
		DropSpotArray[7].setup (mDragLayer, dragController, R.color.drop_target_color1);
		DropSpotArray[7].id=7;

		DropSpotArray[8] = (DropSpot) mDragLayer.findViewById (R.id.drop_spot9);
		DropSpotArray[8].setup (mDragLayer, dragController, R.color.drop_target_color2);
		DropSpotArray[8].id=8;

		DropSpotArray[9] = (DropSpot) mDragLayer.findViewById (R.id.drop_spot10);
		DropSpotArray[9].setup (mDragLayer, dragController, R.color.drop_target_color1);
		DropSpotArray[9].id=9;

		for( int i=0;i<10;i++)
		{
			final int index=i;
			DropSpotArray[index].setOnClickListener(new OnClickListener() {
				@Override
				 public void onClick(View v) {
					int status=-1;
					if(parking_db.serverOn)
					{
						if(index<5)
						{
							if((parking_db.IndexArray_A[index]!=-1)&&(parking_db.listIndex_A!=-1))
							{
								status=parking_db.parkingVector.get(parking_db.listIndex_A).list.get(parking_db.IndexArray_A[index]).parkingStatus;
								if(status==0)
								{
									
									 parking_db.parkingVector.get(parking_db.listIndex_A).list.get(parking_db.IndexArray_A[index]).parkingStatus=1;//unAvailable;
								     DropSpotArray[index].setBackgroundColor(Color.RED);
								     DropSpotArray[index].setSavedBackground(Color.RED);
			
								}
								else
								if(status==1)
								{
									parking_db.parkingVector.get(parking_db.listIndex_A).list.get(parking_db.IndexArray_A[index]).parkingStatus=2;//unKnown; 
						        	DropSpotArray[index].setBackgroundColor(Color.YELLOW);
								     DropSpotArray[index].setSavedBackground(Color.YELLOW);
								}
								else
								if(status==2)
								{
									   parking_db.parkingVector.get(parking_db.listIndex_A).list.get(parking_db.IndexArray_A[index]).parkingStatus=0;//available;  
									   DropSpotArray[index].setBackgroundColor(Color.BLUE);
									     DropSpotArray[index].setSavedBackground(Color.BLUE);

									   
								}
								else
								{
								    DropSpotArray[index].setBackgroundColor(Color.BLACK);
								    DropSpotArray[index].setSavedBackground(Color.BLACK);

								}
								
								
							
							}
							else
							{
						        DropSpotArray[index].setBackgroundColor(Color.BLACK);
							    DropSpotArray[index].setSavedBackground(Color.BLACK);

							}

						}
						else
						{
							if((parking_db.IndexArray_B[index-5]!=-1)&&(parking_db.listIndex_B!=-1))
							{
								
								status=parking_db.parkingVector.get(parking_db.listIndex_B).list.get(parking_db.IndexArray_B[index-5]).parkingStatus;
								switch (status)
								{
									case 0:parking_db.parkingVector.get(parking_db.listIndex_B).list.get(parking_db.IndexArray_B[index-5]).parkingStatus=unAvailable;
									        DropSpotArray[index].setBackgroundColor(Color.RED);
										    DropSpotArray[index].setSavedBackground(Color.RED);

									        break;
									case 1:parking_db.parkingVector.get(parking_db.listIndex_B).list.get(parking_db.IndexArray_B[index-5]).parkingStatus=unKnown; 
									        DropSpotArray[index].setBackgroundColor(Color.YELLOW);
										    DropSpotArray[index].setSavedBackground(Color.YELLOW);

									        break;
									case 2:
											parking_db.parkingVector.get(parking_db.listIndex_B).list.get(parking_db.IndexArray_B[index-5]).parkingStatus=available;  
											DropSpotArray[index].setBackgroundColor(Color.BLUE);
										    DropSpotArray[index].setSavedBackground(Color.BLUE);

									        break;
									default:parking_db.parkingVector.get(parking_db.listIndex_B).list.get(parking_db.IndexArray_B[index-5]).parkingStatus=unKnown;  
									        DropSpotArray[index].setBackgroundColor(Color.BLACK);
										    DropSpotArray[index].setSavedBackground(Color.BLACK);
									        break;
								}
							}
							else
							{
						        DropSpotArray[index].setBackgroundColor(Color.BLACK);
							    DropSpotArray[index].setSavedBackground(Color.BLACK);
							}
							
						}
					}

				}

				
			});
		}
		for( int i=0;i<10;i++)
		{
			final int spot=i;
			DropSpotArray[i].setOnLongClickListener(new View.OnLongClickListener() 
			{
			   public boolean onLongClick(View v) {
			        Log.v( "debug", "LONG CLICK!" );
			    	Intent intent = new Intent(thisActivity, ParkingInfo.class);
			    	intent.putExtra("spotIndex", spot);
			    	thisActivity.startActivity(intent);


			        return true;
			     }
			  }
			);

		}

		// Save the second area so we can enable and disable it via the menu.
		// mSpot2 = drop2;

		// Note: It might be interesting to allow the drop spots to be movable too.
		// Unfortunately, in the current implementation, that does not work
		// because the parent view of the DropTarget objects is not the drag layer.
		// The current DragLayer.onDrop method makes assumptions about how to reposition a dropped view.

		// Give the user a little guidance.
		String message = mLongClickStartsDrag ? "Press and hold to start dragging." 
				: "Touch a view to start dragging.";
		//Toast.makeText (getApplicationContext(), message, Toast.LENGTH_LONG).show ();

	}

	/**
	 * Show a string on the screen via Toast.
	 * 
	 * @param msg String
	 * @return void
	 */

	public void toast (String msg)
	{
		Toast.makeText (getApplicationContext(), msg, Toast.LENGTH_SHORT).show ();
	} // end toast

	/**
	 * Send a message to the debug log and display it using Toast.
	 */

	public void trace (String msg) 
	{
		if (!Debugging) return;
		Log.d ("DragActivity", msg);
	//	toast (msg);
	}


	private final Handler handler = new Handler() {  
		public void handleMessage(Message msg) { 
			  progressDialog.dismiss(); 

			String bundleResult = msg.getData().getString("RESPONSE"); 
//			Toast.makeText( getApplicationContext(),
//					"parking spots edited",Toast.LENGTH_SHORT).show();
			Drawable d= getResources().getDrawable(R.drawable.edited);
			button2.setBackgroundDrawable(d);

		} 
	};
	void performPostRequest()
	{
		LocationViewers.mapView.postInvalidate();
		final ResponseHandler<String> responseHandler = new ResponseHandler<String>() {   
			public String handleResponse(HttpResponse response) {    
				//StatusLine status = response.getStatusLine();        
				HttpEntity entity = response.getEntity();          
				String result = null; 
				try { 
					result = inputStreamToString(entity.getContent());

					Message message = new Message();     
					Bundle bundle = new Bundle();         
					bundle.putString("RESPONSE", result); 
					message.setData(bundle); 
					handler.sendMessage(message);         
				} catch (IOException e) { 
					Log.e("Class6",  " ", e); 
				} 
				return result; 
			} 
		}; 

		// start the progress dialog
		  this.progressDialog = ProgressDialog.show(this, "posting data", "..."); 

		// create and run the thread that perform the request and handle the response
		new Thread() {                          
			@Override 
			public void run() { 
				HttpClient httpclient = new DefaultHttpClient();
				HttpPost httppost = new HttpPost("http://"+parking_db.instanceDNS+":8080/ParkApp/ParkingPost");
				try {

					try
					{
						ref=getSharedPreferences("com.ruthy.parkApp",MODE_PRIVATE);
						String user_id=ref.getString("my_id", "0");

						DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();

						DocumentBuilder docBuilder = builderFactory.newDocumentBuilder();

						//creating a new instance of a DOM to build a DOM tree.
						Document doc = docBuilder.newDocument();
						Element Response = doc.createElement("MSG_TYPE");
						//adding a node after the last child node of the specified node.
						Response.appendChild(doc.createTextNode("USER_POST"));
						doc.appendChild(Response);

						//    Element type=doc.createElement("DATA_LIST");
						//    Response.appendChild(type);
						Element User = doc.createElement("user_id");
						//adding a node after the last child node of the specified node.
						User.appendChild(doc.createTextNode(user_id));
						Response.appendChild(User);

						Element myParking = doc.createElement("myParking");
						myParking.appendChild(doc.createTextNode("-1"));
						User.appendChild(myParking);   

						Element ParkingSpotsList = doc.createElement("ParkingSpotsList");
						//adding a node after the last child node of the specified node.
						User.appendChild(ParkingSpotsList);
						for(int i=0;i<10;i++)//this displays only relevant parking spots (according to T-T-A)
						{
							Element ParkingSpot = doc.createElement("ParkingSpot");
							ParkingSpotsList.appendChild(ParkingSpot);

							Element Spot_ID=doc.createElement("spot_id");
							if(i<5)
								Spot_ID.appendChild(doc.createTextNode(Integer.toString(parking_db.parkingVector.get(parking_db.listIndex_A).list.get(parking_db.IndexArray_A[i]).spotId )));
							else
								Spot_ID.appendChild(doc.createTextNode(Integer.toString(parking_db.parkingVector.get(parking_db.listIndex_B).list.get(parking_db.IndexArray_B[i-5]).spotId )));

							ParkingSpot.appendChild(Spot_ID);
							Element Grid_ID=doc.createElement("grid_id");
							if(i<5)
								Grid_ID.appendChild(doc.createTextNode(Integer.toString(parking_db.parkingVector.get(parking_db.listIndex_A).list.get(parking_db.IndexArray_A[i]).gridID )));
							else
								Grid_ID.appendChild(doc.createTextNode(Integer.toString(parking_db.parkingVector.get(parking_db.listIndex_B).list.get(parking_db.IndexArray_B[i-5]).gridID )));

							ParkingSpot.appendChild(Grid_ID);

							Element Cell_ID=doc.createElement("cell_id");
							if(i<5)
								Cell_ID.appendChild(doc.createTextNode(Integer.toString(parking_db.parkingVector.get(parking_db.listIndex_A).list.get(parking_db.IndexArray_A[i]).cellID )));
							else
								Cell_ID.appendChild(doc.createTextNode(Integer.toString(parking_db.parkingVector.get(parking_db.listIndex_B).list.get(parking_db.IndexArray_B[i-5]).cellID )));

							ParkingSpot.appendChild(Cell_ID);

							Element Status=doc.createElement("status");
							if(i<5)
								Status.appendChild(doc.createTextNode(Integer.toString(parking_db.parkingVector.get(parking_db.listIndex_A).list.get(parking_db.IndexArray_A[i]).parkingStatus )));
							else
								Status.appendChild(doc.createTextNode(Integer.toString(parking_db.parkingVector.get(parking_db.listIndex_B).list.get(parking_db.IndexArray_B[i-5]).parkingStatus )));
							ParkingSpot.appendChild(Status);
							
							Element Type=doc.createElement("type");
							if(i<5)
								Type.appendChild(doc.createTextNode(Integer.toString(parking_db.parkingVector.get(parking_db.listIndex_A).list.get(parking_db.IndexArray_A[i]).ParkingType)));
							else
								Type.appendChild(doc.createTextNode(Integer.toString(parking_db.parkingVector.get(parking_db.listIndex_B).list.get(parking_db.IndexArray_B[i-5]).ParkingType )));

							ParkingSpot.appendChild(Type);

							Element timeToAvailable=doc.createElement("timeToAvailable");
						
							
                            if(i<5)
                            {
                            	if(parking_db.parkingVector.get(parking_db.listIndex_A).list.get(parking_db.IndexArray_A[i]).timeToAvailable!=null)
                            		timeToAvailable.appendChild(doc.createTextNode(parking_db.parkingVector.get(parking_db.listIndex_A).list.get(parking_db.IndexArray_A[i]).timeToAvailable));
                            	else
                            		timeToAvailable.appendChild(doc.createTextNode(now()));		
                            }
                            else
                            {
                            	if(parking_db.parkingVector.get(parking_db.listIndex_B).list.get(parking_db.IndexArray_B[i-5]).timeToAvailable!=null) 
                            		timeToAvailable.appendChild(doc.createTextNode(parking_db.parkingVector.get(parking_db.listIndex_B).list.get(parking_db.IndexArray_B[i-5]).timeToAvailable)); 
                            	else
                            		timeToAvailable.appendChild(doc.createTextNode(now()));
                            }
							ParkingSpot.appendChild(timeToAvailable);
                            

						}


						//TransformerFactory instance is used to create Transformer objects. 
						TransformerFactory factory = TransformerFactory.newInstance();
						Transformer transformer = factory.newTransformer();

						transformer.setOutputProperty(OutputKeys.INDENT, "yes");

						// create string from xml tree
						Log.d("LOGTAG","xml ready to send");

						StringWriter sw = new StringWriter();
						StreamResult result = new StreamResult(sw);
						DOMSource source = new DOMSource(doc);
						transformer.transform(source, result);
						String xmlString = sw.toString();
						Log.d("xmlString","^^^^^^^^^^^^^^^^^^^^"+xmlString);


						StringEntity se = new StringEntity(xmlString); //XML as a string
						se.setContentType("text/xml"); //declare it as XML
						httppost.setEntity(se);



						String response = httpclient.execute(httppost,responseHandler);
						Log.d("","************************************* "+response);





					} catch (ClientProtocolException e) {
						Log.e("LOGTAG", " " , e); 
					} catch (IOException e) {
						Log.e("LOGTAG", " " , e); 
					}
				}
				catch(Exception e)
				{
					Log.e("LOGTAG", " " , e); 
				}


			} 
		}.start(); 
	}



	public static String inputStreamToString(final InputStream stream) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(stream));
		StringBuilder sb = new StringBuilder();
		String line = null;
		while ((line = br.readLine()) != null) {
			sb.append(line + "\n");
		}
		br.close();
		return sb.toString();
	}




	public static String now() {
		Calendar cal = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
		return sdf.format(cal.getTime());
	}

} // end class
